// https://leetcode-cn.com/problems/lru-cache/submissions/

// https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he-shi-xian-by-labuladong/
// 可以总结出 cache 这个数据结构必要的条件：查找快，插入快，删除快，有顺序之分。
// 什么数据结构同时符合上述条件呢？哈希表查找快，但是数据无固定顺序；链表有顺序之分，插入删除快，但是查找慢。所以结合一下，形成一种新的数据结构：哈希链表。
// LRU 缓存算法的核心数据结构就是哈希链表，双向链表和哈希表的结合体。
class BiNode {
public:
    int key;
    int val;
    BiNode* pre;
    BiNode* next;
    BiNode(int key, int val) {
        this->key = key;
        this->val = val;
        this->pre = NULL;
        this->next = NULL;
    }
};

class LRUCache {
private:
    unordered_map<int, BiNode*> cache;
    BiNode* head;
    BiNode* tail;
    int size;
    int capacity;

public:
    LRUCache(int capacity) {
        this->capacity = capacity; 
        this->size = 0;
        //注意这两个的初始化！！
        head = new BiNode(-1, -1);
        tail = new BiNode(-1, -1);
        head->next = tail;
        tail->pre = head;
    }
    
    int get(int key) {
        if (!cache.count(key)) return -1;
        BiNode* node = cache[key];
        moveToHead(node);
        return node->val;
    }
    
    void put(int key, int value) {
        if (!cache.count(key)) {
            BiNode* node = new BiNode(key, value);
            cache[key] = node;
            addToHead(node);
            ++size;
            if (size > capacity) {
                BiNode* removed = removeTail();
                cache.erase(removed->key);
                delete removed;
                --size;
            }
        } else {
            BiNode* node = cache[key];
            node->val = value;
            moveToHead(node);
        }
    }
    
    void addToHead(BiNode* node) {
        node->pre = head;
        node->next = head->next;
        head->next->pre = node; //注意
        head->next = node;
    }

    void removeNode(BiNode* node) {
        node->pre->next = node->next;
        node->next->pre = node->pre;
    }

    void moveToHead(BiNode* node) {
        removeNode(node);
        addToHead(node);
    }

    BiNode* removeTail() {
        BiNode* node = tail->pre;
        removeNode(node);
        return node;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */